package com.laulkar;

import java.io.IOException;
import java.util.ArrayList;

import org.xmlpull.v1.XmlPullParserException;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.os.SystemClock;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

import com.laulkar.activities.AlarmLister;
import com.laulkar.activities.SubwayList;
import com.laulkar.activities.SubwaySelector;
import com.laulkar.dataproviders.DataProvider;
import com.laulkar.dataproviders.MtaStatus;
import com.laulkar.dataproviders.Subway;
import com.laulkar.services.MessengerService;


public class Main extends Activity {

    private PendingIntent mAlarmSender;
    
	/** Messenger for communicating with service. */
	Messenger mService = null;
	/** Flag indicating whether we have called bind on the service. */
	boolean mIsBound;

	private ProgressDialog m_ProgressDialog = null; 

	public static MtaStatus mta_status = null;
	/**
	 * Handler of incoming messages from service.
	 */
	class IncomingHandler extends Handler {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case MessengerService.MSG_GET_STATUS:
				//mCallbackText.setText("Received from service: " + msg.arg1);
				ArrayList<Subway> subways = msg.getData().getParcelableArrayList(MessengerService.SUBWAY_LIST_KEY);
				
				//Subway subway = msg.getData().getParcelable(MessengerService.SUBWAY_LIST_KEY);
				setDataAndUpdateDisplay(subways);
				break;
			default:
				super.handleMessage(msg);
			}
		}
	}


	/**
	 * Target we publish for clients to send messages to IncomingHandler.
	 */
	final Messenger mMessenger = new Messenger(new IncomingHandler());

	/**
	 * Class for interacting with the main interface of the service.
	 */
	private ServiceConnection mConnection = new ServiceConnection() {
		public void onServiceConnected(ComponentName className,
				IBinder service) {
			// This is called when the connection with the service has been
			// established, giving us the service object we can use to
			// interact with the service.  We are communicating with our
			// service through an IDL interface, so get a client-side
			// representation of that from the raw service object.
			mService = new Messenger(service);
			//mCallbackText.setText("Attached.");

			// We want to monitor the service for as long as we are
			// connected to it.
			try {
				Message msg = Message.obtain(null,
						MessengerService.MSG_REGISTER_CLIENT);
				msg.replyTo = mMessenger;
				mService.send(msg);

				// TODO Give it some value as an example.
				msg = Message.obtain(null,
						MessengerService.MSG_GET_STATUS, this.hashCode(), 0);
				mService.send(msg);
			} catch (RemoteException e) {
				// In this case the service has crashed before we could even
				// do anything with it; we can count on soon being
				// disconnected (and then reconnected if it can be restarted)
				// so there is no need to do anything here.
			}

			// As part of the sample, tell the user what happened.
			Toast.makeText(Main.this, R.string.remote_service_connected,
					Toast.LENGTH_SHORT).show();
		}

		public void onServiceDisconnected(ComponentName className) {
			// This is called when the connection with the service has been
			// unexpectedly disconnected -- that is, its process crashed.
			mService = null;
			//mCallbackText.setText("Disconnected.");

			// As part of the sample, tell the user what happened.
			Toast.makeText(Main.this, R.string.remote_service_disconnected,
					Toast.LENGTH_SHORT).show();
		}
	};


	void doBindService() {
		// Establish a connection with the service.  We use an explicit
		// class name because there is no reason to be able to let other
		// applications replace our component.

		bindService(new Intent(Main.this, 
				MessengerService.class), mConnection, Context.BIND_AUTO_CREATE);
		mIsBound = true;
		//mCallbackText.setText("Binding.");
	}


	void doUnbindService() {
		if (mIsBound) {
			// If we have received the service, and hence registered with
			// it, then now is the time to unregister.
			if (mService != null) {
				try {
					Message msg = Message.obtain(null,
							MessengerService.MSG_UNREGISTER_CLIENT);
					msg.replyTo = mMessenger;
					mService.send(msg);
				} catch (RemoteException e) {
					// There is nothing special we need to do if the service
					// has crashed.
				}
			}

			// Detach our existing connection.
			unbindService(mConnection);

			mIsBound = false;
			//mCallbackText.setText("Unbinding.");
		}
	}

	public void setDataAndUpdateDisplay(ArrayList<Subway> status)
	{
        Intent i = new Intent(this, SubwayList.class);
        
        Bundle b = new Bundle();
        //b.putParcelable(SubwayList.SUBWAY_STATUS_KEY, new Subway());
        b.putParcelableArrayList(SubwayList.SUBWAY_STATUS_KEY, status);
        i.putExtras(b);
        startActivityForResult(i, 0);
	}
	
	public void startSubwayList()
	{
        Intent i = new Intent(this, SubwayList.class);
        
       
        startActivityForResult(i, 0);
	}


	public void startSubwaySelector()
	{
		Intent i = new Intent(this, SubwaySelector.class);
       
        startActivityForResult(i, 0);
	}

	public void startTimeSelector()
	{
		 Intent i = new Intent(this, AlarmLister.class);
        
        startActivity(i);
        //startActivityForResult(i, 0);
	}

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.alarm_service);
		//startSubwaySelector();
		//setDisplay();
		//this.m_adapter = new SubwsayAdapter(this, R.layout.main, subway_status);
		//setListAdapter(this.m_adapter);
		//		viewOrders = new Runnable(){
		//            @Override
		//            public void run() {
		//                getOrders();
		//            }
		//        };
		//doBindService();
		mAlarmSender = PendingIntent.getService(this, 0, new Intent(this, MessengerService.class), 0);
		
		   // Watch for button clicks.
        Button button = (Button)findViewById(R.id.start_alarm);
        button.setOnClickListener(mStartAlarmListener);
        button = (Button)findViewById(R.id.stop_alarm);
        button.setOnClickListener(mStopAlarmListener);
		//MtaStatus status = null;
        button = (Button) findViewById(R.id.start_subway_list);
        button.setOnClickListener(mStartSubwayList);
        button = (Button) findViewById(R.id.start_subway_select);
        button.setOnClickListener(mStartSubwaySelector);
        button = (Button) findViewById(R.id.start_time_select);
        button.setOnClickListener(mStartTimeSelector);
		//setDataAndUpdateDisplay(status);
	}
	 private OnClickListener mStartAlarmListener = new OnClickListener() {
	        public void onClick(View v) {
	            // We want the alarm to go off 30 seconds from now.
	            long firstTime = SystemClock.elapsedRealtime();

	            // Schedule the alarm!
	            AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE);
	            am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
	                            firstTime, 30*1000, mAlarmSender);

	            // Tell the user about what we did.
	            Toast.makeText(Main.this, R.string.start_alarm_service,
	                    Toast.LENGTH_LONG).show();
	        }
	    };

	    private OnClickListener mStopAlarmListener = new OnClickListener() {
	        public void onClick(View v) {
	            // And cancel the alarm.
	            AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE);
	            am.cancel(mAlarmSender);

	            // Tell the user about what we did.
	            Toast.makeText(Main.this, R.string.stop_alarm_service,
	                    Toast.LENGTH_LONG).show();

	        }
	    };
	    private OnClickListener mStartSubwayList = new OnClickListener() {
	        public void onClick(View v) {
	            startSubwayList();

	        }
	    };
	    private OnClickListener mStartSubwaySelector = new OnClickListener() {
	        public void onClick(View v) {
	            startSubwaySelector();

	        }
	    };
	    private OnClickListener mStartTimeSelector = new OnClickListener() {
	        public void onClick(View v) {
	            startTimeSelector();

	        }
	    };
	public void setDisplay()
	{
		MtaStatus status = null;
		try {
			status = DataProvider.parseStatus(getResources());
		} catch (XmlPullParserException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 

		//subway_status = status.subways;

	}


	@Override
	protected void onDestroy() {
	    super.onDestroy();
	    doUnbindService();
	}
	
	 


}